import fetch from 'isomorphic-fetch';

//const rootUrl = document.location.protocol+'//localhost:8080/city/index.php/home/api/';
//const backUrl = document.location.protocol+'//localhost:8080/city/index.php/';
//const rootUrl = document.location.protocol+'//192.168.23.155:8080/city/index.php/home/api/';
//const backUrl = document.location.protocol+'//192.168.23.155:8080/city/index.php/';
const rootUrl =  document.location.protocol+'//o2o.96225.com/city/index.php/home/api/';
const backUrl = document.location.protocol+'//o2o.96225.com/city/index.php/';


let commonFetch = (method, url, parameters,options)=> {

    const urlPath = String(url);
    let paraString = '';

    let wholeUrl ;

        wholeUrl = rootUrl + urlPath;

    if (options != null) return fetch(wholeUrl, options);

    let newOptions =  {
        //headers: {
        //    'Accept': 'application/json',
        //    'Content-Type': 'application/json'
        //}
    };
    if (method === 'get') {
        for (let key in parameters) {
            let value = parameters[key];
            if (typeof value === 'object' || Array.isArray(value)) {
                value = JSON.stringify(value);
            }

            let item = key + '=' + value;
            if (paraString.length == 0) {
                paraString = paraString + item;
            } else {
                paraString = paraString + '&' + item;
            }
        }
        if (paraString.length != 0) {
            wholeUrl = wholeUrl + '?' + paraString;
        }
        newOptions.method = 'get';
        return fetch(wholeUrl, newOptions);
    }
    if (method === 'post') {
        newOptions.method = 'post';
        let form = new FormData();
        for (let key in parameters) {
            let value = parameters[key];
            if (typeof value === 'object' || Array.isArray(value)) {
                value = JSON.stringify(value);
            }
            form.append(key,value);
        }
        newOptions.body = form;
        if(url=="login"){
            newOptions.credentials='include';
        }
        return fetch(wholeUrl, newOptions);
    }
    return fetch(wholeUrl + urlPath, options);
};

export let fetchGet = (url, parameters) => {
    return commonFetch('get', url, parameters);
};

export let fetchPost = (url, parameters) => {
    return commonFetch('post', url, parameters);
};
export let getBack=()=>{
    return backUrl;
};
